﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Globalization;
using System.IO;
using DevExpress.Wpf.Editors.Settings;
using Business.Compta;
using DAO.Compta;
using Manageo;



namespace Compta
{
    /// <summary>
    /// Interaction logic for ComptaLine.xaml
    /// </summary>
    public partial class ComptaLineUI : Manageo.INotifierUI
    {
        #region static properties
        public static ObservableRangeCollection<Category> Categories
        {
            get
            {
                try
                {
                    return new ObservableRangeCollection<Category>(ComptaCategoriesDAO.getAllCategories());
                }
                catch (Exception e) 
                { 
                    //MessageBox.Show("error while retrieving categories \n\n" + e, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    return new ObservableRangeCollection<Category>();
                }
            }
        }

        #endregion

        #region Members
        private int idAccount=-1;
        private int idUser = -1;
        private ObservableRangeCollection<ComptaLine> allLines = new ObservableRangeCollection<ComptaLine>();
        private List<ComptaLine> accountLinesSup = new List<ComptaLine>();
        private ObservableRangeCollection<User> users = new ObservableRangeCollection<User>();
        private ObservableRangeCollection<ComptaLineSup> linesSup = new ObservableRangeCollection<ComptaLineSup>();
        private ObservableRangeCollection<Account> accounts = new ObservableRangeCollection<Account>();
        
        private System.ComponentModel.BackgroundWorker deleteBw = new System.ComponentModel.BackgroundWorker();

        public delegate void addLineDelegate(ComptaLine i);
        public delegate ComptaLine getComptaLineDelegate(int i);
        public delegate void removeLineDelegate(ComptaLine i);
        addLineDelegate addLineDel;
        removeLineDelegate removeLineDel;
        getComptaLineDelegate getComptaLineDel;

        ComptaLinesDAO dao = null;

        public ObservableRangeCollection<ComptaLine> AllLines
        {
            get
            {
                if (allLines == null)
                {
                    this.allLines = new ObservableRangeCollection<ComptaLine>();
                }
                return allLines;
            }
        }

        public ObservableRangeCollection<Account> Accounts
        {
            get
            {
                return accounts;
            }
        }

        public ObservableRangeCollection<User> Users
        {
            get
            {
                if (users == null)
                {
                    this.users = new ObservableRangeCollection<User>();
                }
                return users;
            }
        }

        public ObservableRangeCollection<ComptaLineSup> LinesSup
        {
            get
            {
                return linesSup;
            }
        }
        #endregion

        #region constructeur
        public ComptaLineUI(int idUser)
        {
            this.idUser = idUser;
            InitializeComponent();
            accounts.ReplaceRange(ComptaAccountsDAO.getAllAccounts(idUser));
            IsPermanentLayout = true;
            addLineDel = new addLineDelegate(addLine);
            removeLineDel = new removeLineDelegate(removeLine);
            getComptaLineDel = new getComptaLineDelegate(getComptaLine);

            importBw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoImport);
            importBw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(importBw_RunWorkerCompleted);

            deleteBw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoDelete);
            copyBw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoPaste);

            dao = new ComptaLinesDAO();
            dao.Changed += new DAO.IComptaLineNotifier.ChangedEventHandler(ComptaLineUI_Changed);
        }
        #endregion

        #region Compta Lines
        private void view_ValidateRow(object sender, DevExpress.Wpf.Grid.GridRowValidationEventArgs e)
        {
            ComptaLine line = (ComptaLine)e.Row;
            if (line != null)
            {
                e.IsValid = (line.Debit > 0 || line.Credit>0) && line.Date != null;
                if (e.IsValid && line != null)
                {
                    if (line.Id == -1)
                    {
                        try
                        {
                            line.IdAccount = idAccount;
                            line.Id = ComptaLinesDAO.InserNewLine(line);
                            line.commit();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(Window.GetWindow(this), "error while modifying or insert compta line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                            allLines.Remove(line);
                        }
                    }
                    else
                    {
                        try
                        {
                            ComptaLinesDAO.ModifyLine(line);
                            line.commit();
                        }
                        catch (Exception ex)
                        {
                            line.reject();
                            MessageBox.Show("error while modifying or insert compta line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else
                {
                    e.ErrorContent = "Date and Amount must not be null.\n\n";
                }
            }
        }

        private void keyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DevExpress.Wpf.Grid.TableView view = (DevExpress.Wpf.Grid.TableView)sender;
                if (view.ActiveEditor == null || !view.ActiveEditor.IsEditorActive)
                {
                    deleteBw.RunWorkerAsync(view.SelectedRows);
                }
            }
        }
        
        private void bw_DoDelete(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            DeleteRow((DevExpress.Wpf.Grid.SelectedRowsCollection)e.Argument);
        }

        private void DeleteRow(DevExpress.Wpf.Grid.SelectedRowsCollection rows)
        {
            OnBegin(null);
            System.Windows.Threading.Dispatcher aDisp = this.Dispatcher;
            double nbLines = rows.Count;
            int i = 0;
            List<ComptaLine> lines = new List<ComptaLine>();
            foreach (ComptaLine copiedLine in rows)
            {
                lines.Add(copiedLine);
            }
            try
            {
                List<int> results = dao.deleteLines(lines);
                if (results.Count > 0)
                {
                    StringBuilder sp = new StringBuilder();
                    foreach (int result in results)
                    {
                        sp.Append(result);
                        sp.Append(",");
                    } 
                    sp.Remove(sp.Length,1);
                    MessageBox.Show("Certaines lignes n'ont pas été supprimées. Voir Mamour !\n\n ID in (" + sp.ToString() + ")", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Une erreur est survenue pendant la suppression\n\n" + e.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            OnEnded(null);
        }

        private void addLine(ComptaLine line)
        {
            this.allLines.Add(line);
        }

        private void removeLine(ComptaLine line)
        {
            this.allLines.Remove(line);
        }
        
        private ComptaLine getComptaLine(int rowHandle)
        {
            int listIndex = this.gridControl1.GetRowListIndex(rowHandle);
            ObservableRangeCollection<ComptaLine> list =
                (ObservableRangeCollection<ComptaLine>)this.gridControl1.DataSource;
            if (listIndex >= 0)
            {
                return list[listIndex];
            }
            return null;
        }
        #endregion
        
        #region Compta Lines Sup
        private ComptaLine selectedComptaLine = null;
        
        private void ChangeComptaLine(object sender, DevExpress.Wpf.Grid.FocusedRowChangedEventArgs e)
        {
            int listIndex = this.gridControl1.GetRowListIndex(view.FocusedRowHandle);
            if (listIndex >= 0)
            {
                ObservableRangeCollection<ComptaLine> list =
                    (ObservableRangeCollection<ComptaLine>)this.gridControl1.DataSource;
                ComptaLine line = list[listIndex];
                selectedComptaLine = line;
                linesSup.ReplaceRange(ComptaLinesDAO.getLinesSup(line.Id));
            }
        }

        private void validateLineSup(object sender, DevExpress.Wpf.Grid.GridRowValidationEventArgs e)
        {
            if (selectedComptaLine == null)
            {
                int listIndex = this.gridControl1.GetRowListIndex(view.FocusedRowHandle);
                if (listIndex >= 0)
                {
                    ObservableRangeCollection<ComptaLine> list =
                        (ObservableRangeCollection<ComptaLine>)this.gridControl1.DataSource;
                    ComptaLine line = list[listIndex];
                    selectedComptaLine = line;
                }
            }
            ComptaLineSup lineSup = (ComptaLineSup)e.Row;
            if (lineSup != null)
            {
                if (lineSup.Id == -1)
                {
                    try
                    {
                        lineSup.IdLine = selectedComptaLine.Id;
                        lineSup.Id = ComptaLinesDAO.InserNewLineSup(lineSup);
                        lineSup.commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(Window.GetWindow(this), "error while modifying or insert compta line ! (id = " + lineSup.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        linesSup.Remove(lineSup);
                    }
                }
                else
                {
                    try
                    {
                        ComptaLinesDAO.ModifyLineSup(lineSup);
                        lineSup.commit();
                    }
                    catch (Exception ex)
                    {
                        lineSup.reject();
                        MessageBox.Show("error while modifying or insert compta line ! (id = " + lineSup.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        private void deleteLineSup(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DevExpress.Wpf.Grid.TableView view = (DevExpress.Wpf.Grid.TableView)sender;
                if (view.ActiveEditor == null || !view.ActiveEditor.IsEditorActive)
                {

                    int listIndex = this.gridControl1.GetRowListIndex(LinesSupView.FocusedRowHandle);
                    ObservableRangeCollection<ComptaLineSup> list =
                        (ObservableRangeCollection<ComptaLineSup>)this.gridLinesSup.DataSource;
                    if (listIndex >= 0)
                    {
                        ComptaLineSup line = list[listIndex];
                        try
                        {
                            int _return = ComptaLinesDAO.deleteLineSup(line);
                            if (_return == 1)
                            {
                                list.RemoveAt(listIndex);
                            }
                            else
                            {
                                MessageBox.Show("La ligne n'a pas été supprimée. Voir Mamour !", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("error while deleting compta line sup (id = " + line.Id + ")\n" + ex.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }

        }
        
        private void LinesSupView_InitNewRow(object sender, DevExpress.Wpf.Grid.InitNewRowEventArgs e)
        {
            this.gridLinesSup.SetCellValue(e.RowHandle, "Date", selectedComptaLine.Date);
        }
        #endregion

        #region "Import"
        private System.ComponentModel.BackgroundWorker importBw = new System.ComponentModel.BackgroundWorker();
        
        private void selectFile(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.RestoreDirectory = true;
            dlg.DefaultExt = ".csv";
            dlg.Filter = "CSV Files (.csv)|*.csv";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                string pathCsv = dlg.FileName;
                fileName.Text = pathCsv;
            }
        }

        //public ImportFromXls(string file)
        //{
        //MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source="+file+";Extended Properties=Excel 8.0;");
        //MyCommand = new OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        //}

        //public void importFromXls(string file){
        //    MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source="+file+";Extended Properties=Excel 8.0;");
        //    MyCommand = new OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        //DS = new DataSet();
        //try
        //    {
        //    MyCommand.Fill(DS);
        //    return 1;
        //    }
        //catch(Exception ex)
        //    {
        //    Console.WriteLine("Erreur de connection au fichier\n{0}", ex.Message);
        //    return 2;
        //    }
        //finally
        //    {
        //    MyConnection.Close();
        //    }
        //}

        private void importLineByCsv_Click(object sender, RoutedEventArgs e)
        {
                Dictionary<string, object> values = new Dictionary<string, object>();
                values.Add("fileName", this.fileName.Text);
                values.Add("idAccount", this.idAccount);
                importBw.RunWorkerAsync(values);
        }

        void importBw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message + "\n\n" + e.Error.StackTrace, "ERREUR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        void bw_DoImport(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Dictionary<string, object> values = (Dictionary<string, object>)e.Argument;
            import((string)values["fileName"], (int)values["idAccount"]);
        }

        private void import(String filePath, int _idAccount)
        {
            OnBegin(null);
            int i = 0;
            try
            {
                FileStream inStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                MemoryStream storeStream = new MemoryStream();
                string line, category, user, comment;
                Double amount;
                DateTime fdate;
                Boolean isChecked, isPermanent, isComptaLineSup;

                storeStream.SetLength(inStream.Length);
                inStream.Read(storeStream.GetBuffer(), 0, (int)inStream.Length);
                storeStream.Flush();
                inStream.Close();
                StreamReader rdr = new StreamReader(storeStream, System.Text.Encoding.Default);

                while (!rdr.EndOfStream)
                {
                    rdr.ReadLine();
                    i++;
                }
                double lineNumbers = i - 1;

                //rdr = new StreamReader(storeStream, System.Text.Encoding.Default);
                rdr.BaseStream.Position = 0;

                // on supprime les headers !
                if (!rdr.EndOfStream)
                {
                    line = rdr.ReadLine();
                }
                //ImportLine newImportLine;
                ComptaLine cpLine;

                List<ComptaLine> allLines = new List<ComptaLine>();

                int j = 0;
                try
                {
                    i = 0;
                    while (!rdr.EndOfStream)
                    {
                        j = 0;
                        line = rdr.ReadLine();
                        string[] data = line.Split(';');
                        j++;
                        fdate = DateTime.Parse(data[0]);
                        j++;
                        amount = Double.Parse(data[1]);
                        j++;
                        category = data[2];
                        j++;
                        comment = data[3];
                        j++;
                        user = data[4];
                        j++;
                        isChecked = Int32.Parse(data[5]) > 0;
                        j++;
                        isPermanent = Int32.Parse(data[6]) > 0;
                        j++;
                        isComptaLineSup = Int32.Parse(data[7]) > 0;

                        cpLine = new ComptaLine();
                        cpLine.IdAccount = _idAccount;
                        cpLine.Date = fdate;
                        cpLine.Amount = amount;
                        cpLine.IsChecked = isChecked;
                        cpLine.IsPermanent = isPermanent;
                        cpLine.IsComptaLineSup = isComptaLineSup;
                        cpLine.Comment = comment;

                        var cat = from c in Categories
                                  where c.CategoryName == category
                                  select c;
                        foreach (Category Result in cat) cpLine.Category = Result;

                        var usr = from c in this.users
                                  where c.Login == user
                                  select c;
                        foreach (User Result in usr) cpLine.IdUser = Result.Id;

                        allLines.Add(cpLine);
                        OnChanged(new Manageo.NotifyEventArgs((int)(((++i) / lineNumbers) * 100.0), "Analyse des données importées en cours..."));
                    }
                }
                catch (Exception e)
                {
                    throw new ImportException("Problème lors de l'import : \nException pendant l'analyse des données à la ligne "+(i+2)+" - colonne "+j+"\n\n"+e.Message);
                }

                try
                {
                    dao.InserNewLines(allLines);
                }
                catch (Exception e)
                {
                    throw new ImportException("Problème lors de l'import : \n Exception pendant l'insertion en base de données de la ligne " + i + "\n\n" + e.Message);
                }
            }
            finally
            {
                OnEnded(null);
            }
        }

        void ComptaLineUI_Changed(object sender, DAO.NotifyEventArgs e)
        {
            switch (e.Update)
            {
                case DAO.NotifyEventArgs.UpdateEnum.Add:
                    this.Dispatcher.Invoke(addLineDel, System.Windows.Threading.DispatcherPriority.Normal, e.Line);
                    break;

                case DAO.NotifyEventArgs.UpdateEnum.Del:
                    this.Dispatcher.Invoke(removeLineDel, System.Windows.Threading.DispatcherPriority.Normal, e.Line);
                    break;
            }
            
            OnChanged(new Manageo.NotifyEventArgs(e.Advancement, e.Message));
        }      
        #endregion

        #region Export

        private void selectExportDirectory(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1 = 
                new System.Windows.Forms.FolderBrowserDialog();

            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.exportDirectory.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void exportCsv_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                export(this.exportDirectory.Text + @"\" + this.exportFileName.Text + ".csv");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erreur durant l'export \n\n" + ex.Message, "ERREUR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void export(String path)
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms, System.Text.Encoding.Default);
            sw.WriteLine("DATE;MONTANT;CATEGORIE;USER;COMMENT;COMPTABILISÉ;EST PERMANENT;EST SUP");
            //this.gridControl1.FilterCriteria;
            foreach (ComptaLine line in this.allLines)
            {
                sw.Write(line.Date.ToString("dd/MM/yyyy"));
                sw.Write(";");
                sw.Write(line.Amount);
                sw.Write(";");
                sw.Write(line.Category == null ? "" : line.Category.CategoryName);
                sw.Write(";");
                if (line.IdUser != -1)
                {
                    var usr = from c in this.users
                              where c.Id == line.IdUser
                              select c;
                    foreach (User Result in usr) sw.Write(Result.Login);
                }
                else
                {
                    sw.Write("");
                }
                sw.Write(";");
                sw.Write(line.Comment);
                sw.Write(";");
                sw.Write(line.IsChecked ? "1" : "0");
                sw.Write(";");
                sw.Write(line.IsPermanent ? "1" : "0");
                sw.Write(";");
                sw.WriteLine(line.IsComptaLineSup ? "1" : "0");
                sw.Flush();
            }

            FileStream fs = new FileStream(path, FileMode.CreateNew);
            ms.WriteTo(fs);

            ms.Close();
            fs.Close();
        }
        #endregion

        #region gestion Totaux Grille
        double emptyCellsTotalCount = 0;
        double soldAccount = 0;
        private void AllLines_customSummary(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            if (((DevExpress.Wpf.Data.GridSummaryItem)e.Item).FieldName != "Amount")
                return;
            if (e.IsTotalSummary)
            {
                if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Start)
                {
                    emptyCellsTotalCount = soldAccount;
                }
                if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Calculate)
                {
                    double val = (double)e.FieldValue;
                    emptyCellsTotalCount += val;
                    e.TotalValue = emptyCellsTotalCount;
                }
            }
        }
        #endregion
        
        #region affichage Lignes Permanentes
        // DependencyProperty permettant de déterminer la couleur de fond de chaque ligne se fait
        // par catégorie
        // ou par statut permanent ou non
        // voir XAML
        public static readonly DependencyProperty IsPermanentLayoutProperty
             = DependencyProperty.Register("IsPermanentLayout", typeof(Boolean?), typeof(ComptaLineUI));

        public Boolean? IsPermanentLayout
        {
            get
            {
                return this.GetValue(IsPermanentLayoutProperty) as Boolean?;
            }
            set
            {
                this.SetValue(IsPermanentLayoutProperty, value);
            }
        } 

        private void permanentChb_Click(object sender, RoutedEventArgs e)
        {
            IsPermanentLayout = this.permanentChb.IsChecked;
        }
        #endregion

        #region Lignes ComptaLine Sup ?
        private void OnlyCompta_Click(object sender, RoutedEventArgs e)
        {
            CheckBox onlyComptaChb = (CheckBox)sender;
            if (onlyComptaChb.IsChecked == true)
            {
                deleteLinesSup();
            }
            else
            {
                addLinesSup();
            }
        }

        private void deleteLinesSup()
        {
            this.allLines.RemoveRange(this.accountLinesSup);
        }

        private void addLinesSup()
        {
            List<ComptaLineSup> linesSup = ComptaLinesDAO.getLinesSupForAccount(idAccount);
            this.accountLinesSup.Clear();
            foreach (ComptaLineSup lineSup in linesSup)
            {
                this.accountLinesSup.Add(new UILineSup(lineSup));
            }
            this.allLines.AddRange(this.accountLinesSup);
        }
        #endregion

        #region Copy/Paste
        private System.ComponentModel.BackgroundWorker copyBw = new System.ComponentModel.BackgroundWorker(); 
        IEnumerable<int> copyLines = null;
        private void view_CopyToClipboard(object sender, DevExpress.Wpf.Grid.CopyToClipboardEventArgs e)
        {
            copyLines = e.RowHandles;
        }


        private void view_PasteFromClipboard(object sender, DevExpress.Wpf.Grid.PasteFromClipboardEventArgs e)
        {
            copyBw.RunWorkerAsync(copyLines);

        }

        void bw_DoPaste(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            OnBegin(null);
            double nbLine = copyLines.Count<int>();
            int i = 0;
            System.Windows.Threading.Dispatcher aDisp = this.Dispatcher;

            List<ComptaLine> linesToCopy = new List<ComptaLine>();
            IEnumerable<int> _copyLines = (IEnumerable<int>)e.Argument;
            ComptaLine newLine;
            foreach (int rowHandle in _copyLines)
            {
                linesToCopy.Add((ComptaLine)aDisp.Invoke(getComptaLineDel, System.Windows.Threading.DispatcherPriority.Normal, rowHandle));
            }
            foreach (ComptaLine line in linesToCopy)
            {
                if (line !=null) {
                    newLine = new ComptaLine(line);
                    newLine.Id = ComptaLinesDAO.InserNewLine(newLine);
                    newLine.commit();
                    aDisp.Invoke(addLineDel, System.Windows.Threading.DispatcherPriority.Normal, newLine);
                    OnChanged(new Manageo.NotifyEventArgs((int)(((++i)/nbLine)*100.0), "copie des données en cours..."));
                }                
            }
            OnEnded(null);
        }
        #endregion

        #region Layout
        public void saveLayout()
        {
                MemoryStream ms = new MemoryStream();
                this.gridControl1.SaveLayoutToStream(ms);
                DAO.Compta.ComptaUsersDAO.ModifyLayout(ms, idUser);
        }

        public void loadLayout()
        {
                byte[] dAOComptaComptaUsersDAOgetLayout = DAO.Compta.ComptaUsersDAO.getLayout(idUser);
                if (dAOComptaComptaUsersDAOgetLayout != null)
                {
                    MemoryStream ms = new MemoryStream(dAOComptaComptaUsersDAOgetLayout);
                    this.gridControl1.RestoreLayoutFromStream(ms);
                }
        }
        #endregion

        class UILineSup : ComptaLineSup
        {
            public override double Amount
            {
                get
                {
                    return 0;
                }
            }
            public UILineSup(ComptaLineSup ls)
                : base(ls)
            { }
        }
        
        private void gridControl1_Loaded(object sender, RoutedEventArgs e)
        {
            this.gridControl1.Columns["IdUser"].EditSettings = new ComboBoxEditSettings() { DisplayMember = "Login", ValueMember = "Id", ItemsSource = (this.Users) };
        }

        private void gridLinesSup_Loaded(object sender, RoutedEventArgs e)
        {
            this.gridLinesSup.Columns["IdUser"].EditSettings = new ComboBoxEditSettings() { DisplayMember = "Login", ValueMember = "Id", ItemsSource = (this.Users) };
            this.gridLinesSup.Columns["IdAccount"].EditSettings = new ComboBoxEditSettings() { DisplayMember = "AccountNumber", ValueMember = "Id", ItemsSource = (this.Accounts) };
        }

        private void selectAccountCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (idAccount == -1)
            {
                this.gridLinesSup.IsEnabled = true;
                this.importGrid.IsEnabled = true;
                this.exportGrid.IsEnabled = true;
            }
            ComboBox cb = (ComboBox)sender;
            Account acct = (Account)cb.SelectedValue;
            idAccount = acct.Id;
            soldAccount = acct.Sold;
            this.allLines.ReplaceRange(ComptaLinesDAO.getComptaLines(idAccount));
            this.users.ReplaceRange(ComptaUsersDAO.getOwners(idAccount));
            if (OnlyComptaChb.IsChecked == false)
                addLinesSup();
        }
    }

    public class ColorValueConverter : MarkupExtension, IValueConverter
    {
        public int MaxValue { get; set; }

        #region IValueConverter Members
        public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            else
                return new SolidColorBrush((Color)((Category)value).Color);
        }

        public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
        {
            return null;
        }
        #endregion

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}
